package com.njchy.statistics.config;

import com.njchy.statistics.util.QueryWlanAddressUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Arrays;

/**
 * Swagger 美化页doc.html配置
 *
 * @author zxt
 * @since 1.0.0
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${swagger.enable}")
    private Boolean enable;

    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现，
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     *
     * @return
     */
    @Bean
    public Docket restApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(enable)
                .groupName("管线统计模块")
                .apiInfo(apiInfo("管线统计模块", "1.0"))
                .useDefaultResponseMessages(true)
                .forCodeGeneration(false)
                // 添加认证信息（在Swagger UI中可以输入token）
                .securitySchemes(Arrays.asList(
                        new BasicAuth("basicAuth") // 基础认证
                ))
                .securityContexts(Arrays.asList(
                        SecurityContext.builder()
                                .securityReferences(Arrays.asList(
                                        new SecurityReference("basicAuth", new AuthorizationScope[0])
                                ))
                                .build()
                ))
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.njchy.statistics.controller"))
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 创建该API的基本信息（这些基本信息会展现在文档页面中）
     * 访问地址：http://ip:port/doc.html
     *
     * @return
     */
    private ApiInfo apiInfo(String title, String version) {
        return new ApiInfoBuilder()
                .title(title)
                .description("项目接口文档")
                .contact(new Contact("测绘院", QueryWlanAddressUtil.getInt() + "/doc.html", "1478699371@qq.com"))
                .version(version)
                .build();
    }
}